# Windows容器启动脚本
# 专为Windows Server容器和Java Robot API优化
# 支持VNC远程桌面访问

Write-Host "=== Windows游戏自动化容器启动 ===" -ForegroundColor Green

# 设置日志输出
$LogFile = "C:\app\logs\container-startup.log"
Start-Transcript -Path $LogFile -Append

# 启动VNC服务
Write-Host "`n=== 配置VNC远程桌面 ===" -ForegroundColor Green
$vncResult = & "C:\app\setup-vnc.ps1"
if (-not $vncResult) {
    Write-Warning "VNC配置失败，但继续启动应用..."
}

try {
    # 验证Java环境
    Write-Host "验证Java环境..." -ForegroundColor Yellow
    java -version
    if ($LASTEXITCODE -ne 0) {
        throw "Java环境验证失败"
    }

    # 设置Java系统属性（Windows容器优化）
    $env:JAVA_OPTS = "-Djava.awt.headless=false " +
                     "-Djava.security.policy=all.policy " +
                     "-Djava.awt.toolkit=sun.awt.windows.WToolkit " +
                     "-Dfile.encoding=UTF-8 " +
                     "-Xmx2g -Xms512m"

    # 设置Windows特定的Robot API配置
    Write-Host "配置Robot API环境..." -ForegroundColor Yellow
    
    # 确保显示服务可用（Windows容器中的桌面会话）
    $displayService = Get-Service -Name "Themes" -ErrorAction SilentlyContinue
    if ($displayService -eq $null) {
        Write-Warning "桌面服务不可用，某些Robot API功能可能受限"
    }

    # 创建必要的目录结构
    Write-Host "创建目录结构..." -ForegroundColor Yellow
    $directories = @(
        "C:\app\games",
        "C:\app\screenshots", 
        "C:\app\logs",
        "C:\app\scripts",
        "C:\app\config"
    )
    
    foreach ($dir in $directories) {
        if (!(Test-Path $dir)) {
            New-Item -ItemType Directory -Path $dir -Force | Out-Null
            Write-Host "创建目录: $dir" -ForegroundColor Gray
        }
    }

    # 设置屏幕分辨率（如果可能）
    Write-Host "配置显示设置..." -ForegroundColor Yellow
    try {
        # 尝试设置标准分辨率
        # 注意：Windows容器可能没有图形显示，但保留Robot API兼容性
        Add-Type -TypeDefinition @"
        using System;
        using System.Runtime.InteropServices;
        public class DisplaySettings {
            [DllImport("user32.dll")]
            public static extern bool SetDisplayConfig(uint numPathArrayElements, IntPtr pathArray, uint numModeInfoArrayElements, IntPtr modeInfoArray, uint flags);
        }
"@
        Write-Host "显示设置配置完成" -ForegroundColor Gray
    } catch {
        Write-Warning "显示设置配置跳过: $($_.Exception.Message)"
    }

    # 启动应用前的环境检查
    Write-Host "执行环境检查..." -ForegroundColor Yellow
    
    # 检查JAR文件
    if (!(Test-Path "C:\app\app.jar")) {
        throw "应用JAR文件不存在: C:\app\app.jar"
    }

    # 检查Windows游戏支持
    Write-Host "检查Windows游戏运行环境..." -ForegroundColor Yellow
    
    # 检查DirectX支持
    $dxdiag = Get-Command "dxdiag.exe" -ErrorAction SilentlyContinue
    if ($dxdiag) {
        Write-Host "DirectX 支持: 可用" -ForegroundColor Green
    } else {
        Write-Warning "DirectX 可能不完全支持"
    }

    # 检查.NET Framework
    $dotnetVersions = Get-ChildItem "HKLM:SOFTWARE\Microsoft\NET Framework Setup\NDP" -Recurse |
                     Get-ItemProperty -Name Version -ErrorAction SilentlyContinue |
                     Where-Object { $_.PSChildName -match '^v\d+\.\d+' } |
                     Select-Object @{n='Version'; e={$_.Version}}, @{n='Framework'; e={$_.PSChildName}}
    
    if ($dotnetVersions) {
        Write-Host ".NET Framework 支持: 可用" -ForegroundColor Green
        $dotnetVersions | ForEach-Object { Write-Host "  - $($_.Framework): $($_.Version)" -ForegroundColor Gray }
    }

    # 显示容器信息
    Write-Host "`n=== 容器环境信息 ===" -ForegroundColor Cyan
    Write-Host "工作目录: $(Get-Location)" -ForegroundColor Gray
    Write-Host "Java版本: $(java -version 2>&1 | Select-Object -First 1)" -ForegroundColor Gray
    Write-Host "系统架构: $env:PROCESSOR_ARCHITECTURE" -ForegroundColor Gray
    Write-Host "操作系统: $(Get-ComputerInfo | Select-Object -ExpandProperty WindowsProductName)" -ForegroundColor Gray
    
    # 启动Java应用
    Write-Host "`n=== 启动游戏自动化程序 ===" -ForegroundColor Green
    Write-Host "应用程序: C:\app\app.jar" -ForegroundColor Gray
    Write-Host "Java参数: $env:JAVA_OPTS" -ForegroundColor Gray
    
    # 进入应用目录
    Set-Location C:\app
    
    # 启动应用（前台运行）
    Write-Host "正在启动应用程序..." -ForegroundColor Yellow
    & java $env:JAVA_OPTS.Split(' ') -jar app.jar

} catch {
    Write-Error "启动失败: $($_.Exception.Message)"
    Write-Host "错误详情: $($_.Exception)" -ForegroundColor Red
    exit 1
} finally {
    Stop-Transcript
}

# 保持容器运行（如果应用意外退出）
Write-Host "`n应用程序已退出，保持容器运行..." -ForegroundColor Yellow
Write-Host "按 Ctrl+C 停止容器" -ForegroundColor Gray
try {
    while ($true) {
        Start-Sleep -Seconds 30
        Write-Host "." -NoNewline -ForegroundColor Gray
    }
} catch {
    Write-Host "`n容器停止" -ForegroundColor Red
} 